package gameClass;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;

import gameTypes.Drawable;
import gameTypes.Vector2;
import globals.Global;

public class MapChunk implements Drawable {

	public boolean loaded, unload;
	public TileMap tileMap;
	public int dimension;
	public int x, y;
	public Vector2 location;
	
	//testing
	public float fade;
	
	class loadThread extends Thread {
		public loadThread(String str) {
			super(str);
		}
		public void run() {
			tileMap = new TileMap(Global.Instance().chunkSize, Global.Instance().chunkSize);
			try {
				sleep(10);
			} catch (InterruptedException e) {}
			loaded = true;
		}
	}
	
	public MapChunk(int x, int y) { 
		this.x = x;
		this.y = y;
		location = new Vector2(
				Global.Instance().tileSize * Global.Instance().chunkSize * x,
				Global.Instance().tileSize * Global.Instance().chunkSize * y);
		
		//loadThread load = new loadThread("loading");
		//load.start();

		fade = 0.1f;
		tileMap = new TileMap(Global.Instance().chunkSize, Global.Instance().chunkSize);
		loaded = true;
	}
	
	@Override
	public void Update(float elapsed) {
		// Not used
	}

	@Override
	public void Draw(Graphics graphics) {
		if (loaded) {
			// Fade in
			Graphics2D g2d = (Graphics2D) graphics;
			if (fade < 0.95f) {
		        AlphaComposite ac = java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,fade);
		        g2d.setComposite(ac);
		        fade += 0.02;
			}
			
			// Find screen space offset
			int offsetx = (int) (location.x - Global.Instance().camera.location.x);
			int offsety = (int) (location.y - Global.Instance().camera.location.y);
			
			// Draw every tile
	        for (int y = 0; y < Global.Instance().chunkSize; y++) {
	            for (int x = 0; x < Global.Instance().chunkSize; x++) {            	
	            	// Draw to buffer
	            	graphics.drawImage(
	            			// The sprite
	            			Global.Instance().tileImages.get(tileMap.getTile(x, y).index),
	            			// Screen position rectangle
	            			x*Global.Instance().tileSize + offsetx, 
	            			y*Global.Instance().tileSize + offsety,
	            			Global.Instance().tileSize,
	            			Global.Instance().tileSize,
	            			null);
	            }
	        }
	        
	        AlphaComposite ac = java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f);
	        g2d.setComposite(ac);
	        
		}
	}
}
